#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
import mptt
import exceptions

class Board(models.Model):
    name        = models.CharField(max_length=100)
    slug        = models.SlugField(max_length=100)
    parent      = models.ForeignKey('self', null=True, blank=True, related_name='children')
    description = models.TextField(null=True, blank=True)
    topics      = models.PositiveIntegerField(default=0)
    replies     = models.PositiveIntegerField(default=0)
    last_topic  = models.PositiveSmallIntegerField(default=None, null=True, blank=True)
    
    def last(self):
        try:
            return self.last_topic_obj
        except exceptions.AttributeError:
            try:
                self.last_topic_obj = Topic.objects.filter().order_by("-created")[:1][0]
            except IndexError:
                return self.last_topic_obj
            return self.last_topic_obj
    
        
    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        pass

mptt.register(Board, order_insertion_by=['name'])


class AbsTopic(models.Model):
    board    = models.ForeignKey(Board, related_name = '%(class)s_related')
    title    = models.CharField(u'标题', max_length=255)
    author   = models.ForeignKey(User, related_name = '%(class)s_related')
    created  = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True, auto_now_add=True)
    class Meta:
        abstract = True
    
class Topic(AbsTopic):
    last_talk_author = models.ForeignKey(User)
    last_talk_datetime = models.DateTimeField(null=True, blank=True, auto_now_add=True)
    hits = models.PositiveSmallIntegerField(default=0)
    replies = models.PositiveSmallIntegerField(default=0)
    
    class Meta:
        get_latest_by = '-created'

class Talk(AbsTopic):
    ip    = models.IPAddressField(blank=True, default='')
    topic = models.ForeignKey(Topic)
    body  = models.TextField()
    
    def __unicode__(self):
        return self.body
